<template>
	<a-auto-complete
		:class="[
			'app-editor-container',
			'app-auto-complete',
			`app-auto-complete-${name}`,
		]"
		:value="currentVal"
		dropdownClassName="app-editor-autocomplete-dropdown"
		:options="items"
		:filterOption="filterOption"
		:disabled="disabled"
		:open="open"
		@focus="onFoucs"
		@search="onSearch"
		@blur="clearSearch"
	>
		<template #option="item">
			<a-empty
				v-if="items.length == 1 && item.noData"
				:image="simpleImage"
			></a-empty>
			<div v-else @click="onSelect(item[deKeyField])">
				{{ item[deMajorField] }}
			</div>
		</template>
		<a-input :placeholder="placeholder" :allowClear="true" :readOnly="readOnly">
			<template #suffix>
				<SearchOutlined
					v-if="showButton"
					class="certain-category-icon"
					@click="onSearch"
				/>
			</template>
		</a-input>
	</a-auto-complete>
</template>
<script setup lang="ts">
import { Ref, ref } from 'vue';
import { Empty } from 'ant-design-vue';
import { SearchOutlined } from '@ant-design/icons-vue';
import { IParam, IEvent, deepCopy } from '@/core';
import { autoCompleteProps } from './auto-complete';
import { handleEditorNavParams } from '@/hooks/use-editor';
interface EditorEmit {
	(name: 'component-action', value: IEvent<string>): void;
}
const props = defineProps(autoCompleteProps);
const emit = defineEmits<EditorEmit>();
const { navContext, navViewParam } = handleEditorNavParams(props);
let items: Ref<any[]> = ref([]);
let currentVal = computed(() => {
	return props.value ? props.value : searchVal.value;
});
let searchVal = ref('');
const open = ref(false);
const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
const onFoucs = () => {
	open.value = true;
	items.value = [{ noData: true }];
	onSearch('');
};

/**
 * @description 搜索
 * @param value 搜索值
 */
const onSearch = (value: string) => {
	clear();
	searchVal.value = value;
	const _navContext = deepCopy(navContext);
	const _navViewParam = deepCopy(navViewParam);
	Object.assign(_navViewParam, { query: value, size: 1000 });
	if (props.sort) {
		Object.assign(_navViewParam, { sort: props.sort });
	}
	const requestException: string = App.ts(
		'common.generic.requestexception',
		'请求异常'
	);
	if (!props.service) {
		console.warn(App.ts('common.generic.noservice', '服务不存在'));
	} else if (!props.acParams) {
		console.warn(App.ts('common.generic.miss', '参数不存在'));
	} else {
		const { serviceName, interfaceName } = props.acParams;
		const { deKeyField, deCodeName } = props;
		props.service
			.getItems(
				serviceName,
				interfaceName,
				_navContext,
				_navViewParam,
				deKeyField,
				deCodeName
			)
			.then((response: any) => {
				if (!response) {
					console.warn(App.ts('common.generic.loadfail', '加载数据失败'));
					return;
				} else {
					if (response.length == 0) {
						items.value = [{ noData: true }];
					} else {
						items.value = handleDataItems([...response]);
					}
				}
			})
			.catch((error: any) => {
				console.warn(
					error && error.message ? error.message : `代码表${requestException}`
				);
			});
	}
};

const handleDataItems = (opts: any) => {
	if (props.dataItems && props.dataItems.length > 0) {
		if (opts && opts.length > 0) {
			for (let element of opts) {
				for (let item of props.dataItems as Array<any>) {
					if (!item.customCode) {
						if (item.getPSAppDEField()?.codeName) {
							element[item.name] =
								element[item.getPSAppDEField().codeName.toLowerCase()];
						}
					}
				}
				// 先计算非脚本的数据项，防止数据有误
				for (let item of props.dataItems as Array<any>) {
					if (item.customCode) {
						let data = element;
						element[item.name] = eval(`${item.scriptCode}`);
					}
				}
			}
		}
	}
	return opts;
};

const filterOption = (inputValue: string, option: IParam) => {
	if (option[props.deMajorField]) {
		return (
			option[props.deMajorField]
				.toUpperCase()
				.indexOf(inputValue.toUpperCase()) >= 0
		);
	} else {
		return false;
	}
};

const onSelect = (value: any) => {
	open.value = false;
	const selectItem = items.value.find((item: IParam) =>
		Object.is(item[props.deKeyField], value)
	);
	emit('component-action', {
		name: `${props.name}`,
		action: 'valueChange',
		data: selectItem[props.deMajorField],
	});
};

const clear = () => {
	if (props.name) {
		emit('component-action', {
			name: `${props.name}`,
			action: 'valueChange',
			data: '',
		});
	}
};

const clearSearch = () => {
	searchVal.value = '';
	open.value = false;
};
</script>
